package com.boco.blch.runner.executor;

import java.awt.event.KeyEvent;
import java.io.IOException;
import java.io.OutputStream;

import com.boco.blch.runner.command.Command;
import com.boco.blch.runner.login.UserInfo;
import com.boco.blch.runner.result.Result;
import com.boco.blch.runner.result.ResultInfo;
import com.boco.blch.runner.util.ErrorMessageUtil;
import com.boco.blch.runner.util.ObjectUtil;
import com.trilead.ssh2.Session;

public class CommandExecutor extends AbstractExecutor implements Executor {

	
	
	private Command command;
	private Session session;
	private OutputStream os;
	
	public CommandExecutor(UserInfo userInfo, Command command) throws IOException {
		conn = userInfo.login();
		session = conn.openSession();
		this.command = command;
	}

	@Override
	public Result execute() {
		try {
			if (command.getCommand() == null || command.getCommand().equals(""))
				return new ResultInfo(false, 130, ErrorMessageUtil.getErrorMessageByErrorCode(130));
//			return executeAsSimple_();
			return executeAsTerminal(session, command.getCommand());
		} catch (Throwable t) {
			t.printStackTrace();
			return new ResultInfo(false, 129, ErrorMessageUtil.getErrorMessageByErrorCode(129));
		} finally {
			close(session);
		}
	}
	
	private Result executeAsSimple_(){
		String filename = ObjectUtil.filenameGenerator("sh");
		os = session.getStdin();
		Session newSession = null;
		try {
			//创建脚本
			createShellScriptBySFTPv3(filename, command.getCommand());
			//修改权限
			session.execCommand("chmod +x " + filename);
			//关闭此session
			os.close();
			session.close();
			
			//开启一个新session
			newSession = conn.openSession();
			//执行脚本
			newSession.execCommand("./" + filename);

			String result = getSuccessInfoFromSession(newSession);
			String error = getErrorInfoFromSession(newSession);

			if (error != null && !error.trim().equals("")) {
				return new ResultInfo(false, newSession.getExitStatus(), error);
			}

			return new ResultInfo(true, 0, result);

		} catch (Exception e) {
			/*
			 * 捕捉session.execCommand抛出的异常，根据源码解释，此异常出现的原因就是
			 * "A remote execution has already started."
			 */
			return new ResultInfo(false, 128, e.getMessage());

		} finally {
			delShellScriptBySFTPv3(filename, conn);
			newSession.close();
		}
	}
	
	

	/* 简单执行 */
	private Result executeAsSimple() {
		String filename = ObjectUtil.filenameGenerator("sh");
		os = session.getStdin();
		Session newSession = null;
		try {
			//创建脚本
			createShellScriptBySFTPv3(filename, command.getCommand());
			//修改权限
			os.write(chmod(filename).getBytes());os.write(KeyEvent.VK_ENTER);
			//关闭此session
			session.close();
			
			//开启一个新session
			newSession = conn.openSession();
			//执行脚本
			newSession.execCommand("./" + filename);

//			session.waitForCondition(ChannelCondition.EXIT_STATUS, 2000);

			String result = getSuccessInfoFromSession(newSession);
			//String error = getErrorInfoFromSession(newSession);

		//	if (error != null && !error.trim().equals("")) {
		//		return new ResultInfo(false, newSession.getExitStatus(), error);
		//	}

			return new ResultInfo(true, 0, result);

		} catch (Exception e) {
			/*
			 * 捕捉session.execCommand抛出的异常，根据源码解释，此异常出现的原因就是
			 * "A remote execution has already started."
			 */
			return new ResultInfo(false, 128, e.getMessage());

		} finally {
			//删除脚本
			try {
				os.close();
				newSession.close();
				delShellScriptBySFTPv3(filename, conn);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	
}